class Document < ActiveRecord::Base
	
	extend Permissible
	
    attr_accessible :name, :description, :authors, :publication_date, :related_work, :owner,
		:categories, :tags, :files, :comments, :created_by, :updated_by
	
	translates :name, :description
	
	# Validations:
	#validates :name, presence: true
    
    # Relationships:
    belongs_to :owner, class_name: 'User'
    has_and_belongs_to_many :categories
    has_and_belongs_to_many :tags
    has_many :files, class_name: 'DataFile', dependent: :destroy
	has_many :comments, dependent: :destroy
	
    def storage_path
        "public/files/#{self.id}"
    end
    
    def remove
		self.tags.each { |tag| tag.decrement_reference_count }
        FileUtils.rm_rf(storage_path) #remove directory with all files
		self.destroy
    end
	
	def self.create_with_default_permissions(params)
		params[:tags] = Tag.string_to_tags(params[:tags], params[:owner], true)
		params[:publication_date] = Date.parse(params[:publication_date]) unless params[:publication_date].blank?
		
        #save params[:files] = files in directory /public/data
        files_param = params[:files]
        params.delete(:files)
        
		document = Document.create(params)
        
        files = DataFile.save_files(files_param, document)
        files.each do |f|
            document.files.build(
                path: f.path, 
                mime_type: MIME::Types.type_for(f.path).first.content_type, 
                file_size: f.size,
                created_by: document.owner.id)
        end
        
        document.save
		
		if document.errors.none?
			logger.debug('CREATING DEFAULT PERMISSIONS FOR DOCUMENT!')
			create_default_owner_permissions(document, document.owner)
		end
		
		return document
	end
	
	def self.search(search)
		if search
			where('document_translations.name ILIKE ? or document_translations.description ILIKE ?',
				"%#{search}%", "%#{search}%")
		else
			scoped
		end
	end

    def rate

    end
end
